package cloudoer.blog.base;

import cloudoer.blog.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;

public abstract class BaseController {
    private final String[] FILE_TYPE = new String[]{".jpg",".png",".ico",".gif",".jpeg"};

    @Resource(name = "articleService")
    protected ArticleService articleService;
    @Resource(name = "commentService")
    protected CommentService commentService;
    @Resource(name = "menuService")
    protected MenuService menuService;
    @Resource(name = "typeService")
    protected TypeService typeService;
    @Resource(name = "userService")
    protected UserService userService;
    @Resource(name = "tagService")
    protected TagService tagService;
    @Resource(name = "emailService")
    protected EmailService emailService;


    /**
     * 返回请求成功的信息
     * @param message
     * @return
     */
    protected Map<String, Object> success(String message){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("flag","success");
        map.put("message",message);
        return map;
    }

    /**
     * 返回请求错误信息
     * @param message
     * @return
     */
    protected Map<String, Object> error(String message){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("flag","error");
        map.put("message",message);
        return map;
    }

    /**
     * 返回layui table的数据信息
     * @param list
     * @return
     */
    protected Map<String, Object> getMap(List list){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", list);
        map.put("code",0);
        map.put("msg","");
        map.put("count",list.size());
        return map;
    }

    /**
     * 保存图片
     * @param image
     * @param id
     * @param filePath
     * @return
     * @throws IOException
     */
    protected Map<String, Object> saveImage(MultipartFile image, String id, File filePath) throws IOException {
        //文件名
        String fileName = image.getOriginalFilename();
        //类型
        String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        //判断类型
        if (!Arrays.asList(FILE_TYPE).contains(fileExt)){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", 1);
            map.put("message", "文件类型错误");
            return map;
        }
        //使用UUID获取文件名称
        String newName = UUID.randomUUID().toString().replaceAll("-","")+fileExt;
        String imageURL = filePath + "/" + newName;
        image.transferTo(new File(imageURL));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("error", 0);
        map.put("url", "/file/"+id+"/"+newName);
        map.put("message", "上传成功");
        return map;
    }
}
